import requests
from datetime import datetime, timedelta
import json
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
import time

def fetch_data(start_time, end_time, time_delta_label):
    base_url = "https://sqfb.slt.zj.gov.cn/rest/newList/getNewTotalRainList"
    params = {
        "areaFlag": "1",
        "sss": "衢州市",
        "ssx": "",
        "st": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "et": end_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "ly": "",
        "max": "",
        "min": "0",
        "bool": "false",
        "bxdj": "1,2,3,4,5,",
        "zm": "",
        "type": "0",
        "lx": "QX,ME,SX,DS"
    }

    headers = {
        "User-Agent": "Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"
    }

    response = requests.get(base_url, params=params, headers=headers, verify=False)
    response.encoding = "utf-8"

    if response.status_code != 200:
        print(f"请求失败，状态码：{response.status_code}")
        return pd.DataFrame()  # 返回空的DataFrame

    try:
        data = json.loads(response.text)
    except json.JSONDecodeError as e:
        print(f"JSON解析错误：{e}")
        return pd.DataFrame()  # 返回空的DataFrame

    merged_list = [value for value_list in data.values() for value in value_list]

    data1 = []
    for line in merged_list:
        data1.append(line)

    df = pd.DataFrame(data1)
    df['时间段'] = [time_delta_label] * len(df)

    return df

def fetch_monthly_data(year, month):
    start_date = datetime(year, month, 1)
    next_month = start_date.replace(day=28) + timedelta(days=4)
    end_date = next_month - timedelta(days=next_month.day)
    
    all_data = pd.DataFrame()

    current_date = start_date
    while current_date <= end_date:
        next_date = current_date + timedelta(days=1)
        df = fetch_data(current_date, next_date, current_date.strftime("%Y-%m-%d"))
        all_data = pd.concat([all_data, df], ignore_index=True)
        current_date = next_date
        time.sleep(1)  # 每次请求之间等待1秒
    
    return all_data

def save_monthly_data_to_excel(year, start_month, end_month, output_directory):
    for month in range(start_month, end_month + 1):
        monthly_data = fetch_monthly_data(year, month)
        if monthly_data.empty:
            print(f"{year}年{month}月的数据为空或获取失败。")
            continue

        pivoted_data = monthly_data.pivot_table(
            index=['zm', 'jd', 'wd'],
            columns='时间段',
            values='yl',
            aggfunc='first'
        ).reset_index()

        x_values = pivoted_data["jd"]
        y_values = pivoted_data["wd"]

        geometry = [Point(xy) for xy in zip(x_values, y_values)]
        gdf = gpd.GeoDataFrame(pivoted_data, geometry=geometry)
        gdf.set_crs(epsg=4326, inplace=True)

        excel_file = f"{output_directory}/monthly_result_{year}_{month:02d}.xlsx"
        pivoted_data.to_excel(excel_file, sheet_name="雨量", startcol=0, index=False)

        print(f"数据已输出到 {excel_file}")

# 指定年份和输出目录
year = 2019
output_directory = r"G:\2023工作\suan"

# 提取并保存该年份1月至12月的数据
save_monthly_data_to_excel(year, 1, 12, output_directory)
